const DB_NAME = 'my-database'
const DB_VERSION = 1
let db: IDBDatabase
function openDB(): Promise<void> {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION)
    request.onerror = (event) => {
      reject((event.target as IDBOpenDBRequest).error)
    }
    request.onsuccess = (event) => {
      db = (event.target as IDBOpenDBRequest).result
      resolve()
    }
    request.onupgradeneeded = (event) => {
      db = (event.target as IDBOpenDBRequest).result
      if (!db.objectStoreNames.contains('my-store')) {
        db.createObjectStore('my-store', {
          keyPath: 'id',
          autoIncrement: true,
        })
      }
    }
  })
}
export default {
  async addData(key: string, value: any): Promise<void> {
    await openDB()
    const tx = db.transaction('my-store', 'readwrite')
    const store = tx.objectStore('my-store')
    store.add({
      id: key,
      data: JSON.stringify(value),
    })
  },
  async getData(key: string): Promise<any> {
    await openDB()
    return new Promise((resolve, reject) => {
      const tx = db.transaction('my-store', 'readonly')
      const store = tx.objectStore('my-store')
      const request = store.get(key)
      request.onsuccess = (event) => {
        const data = (event.target as IDBRequest).result
        if (data) {
          data.data = JSON.parse(data.data)
          resolve(data)
        } else {
          resolve(false)
        }
      }
      request.onerror = (event) => {
        reject((event.target as IDBRequest).error)
      }
    })
  },
  async deleteData(key: string): Promise<void> {
    await openDB()
    const tx = db.transaction('my-store', 'readwrite')
    const store = tx.objectStore('my-store')
    store.delete(key)
  },
  async updateData(key: string, newValue: any): Promise<void> {
    await openDB()
    const tx = db.transaction('my-store', 'readwrite')
    const store = tx.objectStore('my-store')
    const getRequest = store.get(key)
    getRequest.onsuccess = (event) => {
      const data = (event.target as IDBRequest).result
      if (data) {
        data.data = JSON.stringify(newValue)
        store.put(data)
      }
    }
  },
}
